<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    //     function extractPersonInfo(str) {
    //       const lines = str.split(/\r?\n/); // 按行分割字符串，考虑Windows和Unix/Linux的换行符  
    function parseIdentityInfo(identityLine) {
      // 清理两端空白字符
      identityLine = identityLine.trim();

      // 尝试按身份证格式解析
      const idCardPattern = /^(\s*[^\s]+\s+)?(\d{15}|\d{18})$/;
      const idCardMatch = identityLine.match(idCardPattern);

      if (idCardMatch) {
        const [, name, idNumber] = idCardMatch;
        return {
          type: '身份证',
          name: name ? name.trim() : null,
          idNumber: idNumber,
        };
      }

      // 尝试按护照格式解析
      const passportPattern = /^(\s*[^\s]+\s+)?([A-Z]{1,2}\d{7,9})(\s+(\d{4}[-\/]?[01]\d[-\/]?\d{2}))?$/;
      const passportMatch = identityLine.match(passportPattern);

      if (passportMatch) {
        const [, name, passportNumber, , birthDateStr] = passportMatch;
        const birthDate = new Date(birthDateStr.replace(/[-\/]/g, '/')); // 处理日期格式
        if (!isNaN(birthDate.getTime())) { // 验证日期是否有效
          return {
            type: '护照',
            name: name ? name.trim() : null,
            passportNumber: passportNumber,
            birthDate: birthDate.toISOString().substring(0, 10), // 返回标准化的ISO格式日期
          };
        }
      }

      // 如果既不符合身份证也不符合护照格式，则返回错误信息
      return { error: '无法识别该身份信息，请确保格式正确并重新尝试' };
    }

    // 测试用例
    const testCases = [
      '张三    310101198001015898',
      '310101198001015898 张三',
      '王二   G12346578   1980-01-01',
      '王二   G12346578    1980-7-25',
      '王二   G12346578   1980/7/25',
      '王二   G12346578  19800725',
    ];

    testCases.forEach(testCase => {
      console.log(parseIdentityInfo(testCase));
    });
  </script>
</body>

</html>